package com.mjk.common.tools.gson.adapter.impl;

import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.util.TimeUtils;

import java.io.IOException;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * localdatetime 序列化转换器
 */
public class LocalDateTimeAdapterImpl extends TypeAdapter<LocalDateTime> {
    @Override
    public void write(JsonWriter jsonWriter, LocalDateTime localDateTime) throws IOException {
        if(localDateTime==null){
            jsonWriter.value("");
            return;
        }
        jsonWriter.value(localDateTime.format(DateTimeFormatter.ofPattern(TimeUtils.DATE_FORMAT_DATETIME)));
    }

    @Override
    public LocalDateTime read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            return null;
        }
        return LocalDateTime.ofInstant(TimeUtils.parse(in.nextString()).toInstant(), ZoneId.systemDefault());
    }
}
